package com.ashbur.SelectionSort;

/**
 * @author : Eumenides
 * @Description : 选择排序算法
 * @date : 2022/7/18
 * @Copyright ： 公众号：菜鸟的大厂梦
 */
public class SelectionSort {

    private SelectionSort() {}

    public static <E extends Comparable<E>> void sort(E[] arr) {

        for (int i = 0; i < arr.length; i++) {
            // 选择 arr[i...n) 中最小值的索引
            int minIndex = i;
            for (int j = i; j < arr.length; j++) {
                if (arr[j].compareTo(arr[minIndex]) < 0) {
                    minIndex = j;
                }
            }
            // 交换位置
            swap(arr, i, minIndex);
        }
    }

    private static <E> void swap(E[] arr, int i, int j) {
        E t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args) {

        Integer[] arr = {1,4,2,3,6,5};

        SelectionSort.sort(arr);

        for (int e:
             arr) {
            System.out.print(e);
        }

        Student[] students = {new Student("Alice", 98),
                new Student("Bobo", 100),
                new Student("Charles", 66)};
        SelectionSort.sort(students);
        for(Student student: students) {
            System.out.print(student + " ");
        }
        System.out.println();
    }
}
